<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,team_id,level_id,team_boxes,small_boxes,big_boxes');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,team_id,level_id,team_boxes,small_boxes,big_boxes');
    }

    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_id -- 推荐人的ID
     * @return array
     */
    public function record($uid, $code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_id) {
                $p_id = $parent_id;
                $insert = [];
                while ($parent = User::where('id', $p_id)->field('id,code,parent_id')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_id = $parent->parent_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }


    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus($uid, $total, $recoil_count): array
    {
        try {

            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $poor = 0;
            $level_id = 0;
            $expendTotal = 0;
            $flat = 0;
            $flat_open = true;
            $recoil_tp = Cache::get('system')['recoil_tp'];
            //$flat_total = 0;
            foreach ($list as $item) {
                if ($item->user->is_active != 2 || $item->user->is_out) continue;
                //大区加速
                if ($item->user->recoil_count <= 1 && $recoil_count <= 1) {
                    //大区加速
                    $areaAll = User::where('parent_id', $item->uid)->order('team_total', 'desc')
                        ->column('my_total+team_total as team_total,id');
                    $max_speed = Cache::get('system')['max_speed'];
                    if (!empty($areaAll) && $max_speed > 0 && count($areaAll) > 1) {
                        $max = array_shift($areaAll);
                        $ids = Relation::where(['uid' => $max['id']])->column('new_uid');
                        $ids[] = $max['id'];
                        if (in_array($uid, $ids)) {
                            $amount = UserRelease::testingCapping($item->uid, round($total * $max_speed, 2));
                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '大市场加速', '+')
                                ->createBonus($uid, 5);
                        }
                    }
                }
                //直推
                if ($item->algebra == 1) {
                    $count = User::where(['is_active' => 2, 'parent_id' => $item->uid])->count();
                    $tp = $count >= 3 ? Cache::get('system')['speed_3'] : Cache::get('system')['speed_' . $count];
                    $amount = UserRelease::testingCapping($item->uid, round($total * $tp, 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;
                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '消费分润', '+')
                            ->createBonus($uid, 2);
                    }
                }
                //团队奖
                $level = Level::where('id', $item->user->level_id)->find();
                if (empty($level)) continue;
                if ($item->user->level_id > $level_id && $level->tp > $poor) {
                    $amount = UserRelease::testingCapping($item->uid, round($total * ($level->tp - $poor), 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;

                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '培育分润', '+')
                            ->createBonus($uid, 3);
                    }
                    $poor = $level->tp;
                    $level_id = $item->user->level_id;
                    $flat = $item->user->level_id;
                    $flat_open = true;
                    //$flat_total = $amount;
                } else {

                    if ($item->user->level_id == $flat && $flat_open) {
                        $amount = UserRelease::testingCapping($item->uid, round($total * $level->flat_tp, 2));
                        if ($amount > 0) {

                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '平级奖', '+')
                                ->createBonus($uid, 4);

                            $expendTotal += $amount;
                        }
                        $flat_open = false;
                    }
                }
            }
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function awardPrizes($u_id,$amount,$msg,$fx,$source,$category)
    {
        if($amount>0)
        {
            $tax = Cache::get('system')['tax'];
            $tax_num = bcmul((string)$amount, (string)$tax, 2);
            $bonus = $amount - $tax_num;
            Target::Account()->basics($u_id, 'bonus',$amount,$bonus, $msg, $fx)
                ->createBonus($source, $category);

            Event::trigger('Statistics', ['key' => 'expend', 'value' => $amount]);
        }

    }


    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $min_total = User::geMinTeam($item->user->id);
                $level = Level::where('id', '>', $item->user->level_id)
                    ->where('min_team', '<=', $min_total)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function recommend($p_uid,$boxes_num,$uid)
    {
        try {
            $repurchase_1 = Cache::get('system')['repurchase_1'];
            $amounts = bcmul((string)$repurchase_1, (string)$boxes_num, 2);
            Relation::awardPrizes($p_uid,$amounts,'复购奖', '+',$uid, 6);
            $p_user = User::where('id',$p_uid)->find();
            if($p_user->parent_id)
            {
                $repurchase_2 = Cache::get('system')['repurchase_2'];
                $amounts_2 = bcmul((string)$repurchase_2, (string)$boxes_num, 2);
                Relation::awardPrizes($p_user->parent_id,$amounts_2,'复购奖', '+',$uid, 6);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }



    public static function coaching_award($u_id,$amount)
    {
        try {
            $user = User::find($u_id);
            $users = User::where(['parent_id'=>$user->id,'is_active'=>2])->column('id');
            if($users)
            {
                $coaching_award_1= Cache::get('system')['coaching_award_1'];
                $num = count($users);
                $coaching_amount = bcmul((string)$amount,(string)$coaching_award_1,2);
                $amounts = bcdiv($coaching_amount, (string)$num,2);
                foreach ($users as $k=>$v)
                {
                    Relation::awardPrizes($v,$amounts,'辅导奖', '+',$user->id, 5);
                }

            }

            if($user->parent_id)
            {
                $p_user = User::where('id',$user->parent_id)->find();
                $p_num = User::where('parent_id',$p_user->id)->count();
                $coaching_award_2 = Cache::get('system')['coaching_award_2'];
                if ($p_num>=$coaching_award_2)
                {
                    $coaching_award_4 = Cache::get('system')['coaching_award_4'];
                    $coaching_amount_2 = bcmul((string)$amount,(string)$coaching_award_4,2);
                    Relation::awardPrizes($p_user->id,$coaching_amount_2,'辅导奖', '+',$user->id, 5);
                }

                if($p_user->parent_id)
                {
                    $pp_num = User::where('parent_id',$p_user->parent_id)->count();
                    $coaching_award_3 = Cache::get('system')['coaching_award_3'];
                    if ($pp_num>=$coaching_award_3)
                    {
                        $coaching_award_5 = Cache::get('system')['coaching_award_5'];
                        $coaching_amount_3 = bcmul((string)$amount,(string)$coaching_award_5,2);
                        Relation::awardPrizes($p_user->parent_id,$coaching_amount_3,'辅导奖', '+',$user->id, 5);
                    }

                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    //服务费
    public static function service_charge($recommend_shop,$num,$uid)
    {
        try {
            $service_charge= Cache::get('system')['service_charge'];
            $amount = bcmul((string)$service_charge,(string)$num,2);
            Relation::awardPrizes($recommend_shop,$amount,'服务费', '+',$uid, 7);
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //分红
    public static function bonus()
    {
       $news_boxes = User::where('news_boxes','>',0)->sum('news_boxes');
       if($news_boxes)
       {
           $level = TeamLevel::where('delete_time',0)->select();
           foreach ($level as $k=>$v)
           {
               $users = User::where(['team_id'=>$v->id,'delete_time'=>0])->column('id');
               $num = count($users);
               if($num)
               {
                   $amounts = bcmul((string)$news_boxes,(string)$v->bonus,2);
                   $bonus = bcdiv($amounts, (string)$num,2);
                   foreach ($users as $key=>$value)
                   {
                       Relation::awardPrizes($value,$bonus,'分红', '+',$value, 8);
                   }
               }

           }
           User::where('news_boxes','>',0)->update(['news_boxes'=>0]);
       }
        return ['code' => 1, 'msg' => '分红成功'];
    }
}
